import { Injectable } from '@angular/core';
import { each, filter, find } from 'lodash';

@Injectable({
  providedIn: 'root'
})
export class EventService {
  _events = [];

  // 事件订阅
  public subscribe(name, fn) {
    let event = find(this._events, { name });

    if (event) {
      event.callbacks.push(fn);
    } else {
      event = {
        name,
        callbacks: [fn],
        lastEmitValue: null
      };

      this._events.push(event);
    }
  }

  // 事件推送
  public emit(name, ...params) {
    const event = find(this._events, { name });

    if (event) {
      each(event.callbacks, (cb: () => void) => cb.apply(this, params));

      event.lastEmitValue = params;
    }
  }

  // 取消订阅
  public unsubscribe(name) {
    this._events = filter(this._events, item => item.name !== name);
  }

  // 获取最后一次发送的值
  public lastEmitValue(name) {
    const event = find(this._events, { name });
    return event ? event.lastEmitValue : null;
  }
}
